import React, { useEffect, useState } from "react";
import styles from "@/styles/NodeComponentDisplay.module.sass";
import CUNode from "./NodeComponents/CUNode";
import VisCUNode from "@/types/VisCUNode";
import ArrowCanvas from "./ArrowCanvas";
import $ from "jquery";
import hash from "object-hash";

export default function NodeComponentDisplay(props: {
  leftCu?: VisCUNode;
  rightCu?: VisCUNode;
  leftRanges?: Range[];
  rightRanges?: Range[];
}) {
  const { leftCu, rightCu, leftRanges, rightRanges } = props;
  const [arrows, setArrows] = useState<Array<JSX.Element | undefined>>([]);

  useEffect(() => {
    if (leftRanges && rightRanges && leftRanges.length && rightRanges.length) {
      const leftElements = leftRanges.map((range) =>
        $("#leftCu").find(`.${hash(range)}`)
      );
      const rightElements = rightRanges.map((range) =>
        $("#rightCu").find(`.${hash(range)}`)
      );

      // 目前n:nd对应情况处理为全部画出箭头（n²个）
      setArrows(
        leftElements
          .map((leftE: JQuery<HTMLElement>, indexLeft) => {
            return rightElements.map((rightE, indexRight) => {
              return (
                <ArrowCanvas
                  key={
                    hash(leftRanges) +
                    hash(rightRanges) +
                    indexLeft +
                    indexRight
                  }
                  startDom={leftE.get(0) as HTMLElement}
                  endDom={rightE.get(0) as HTMLElement}
                />
              );
            });
          })
          .flat(2)
      );
    }
    const toggleDeletedOrAddedClass = () => {
      if (leftRanges && rightRanges && leftRanges.length && rightRanges.length)
        return;
      if (leftRanges && leftRanges.length) {
        const leftElements = leftRanges.map((range) =>
          $("#leftCu").find(`.${hash(range)}`)
        );
        leftElements.map((leftE) => {
          leftE.toggleClass(styles.deletedNode);
        });
      } else if (rightRanges) {
        const rightElements = rightRanges.map((range) =>
          $("#rightCu").find(`.${hash(range)}`)
        );
        rightElements.map((rightE) => {
          rightE.toggleClass(styles.addedNode);
        });
      }
    };
    toggleDeletedOrAddedClass();

    // clear the effects
    return () => {
      setArrows([]);
      toggleDeletedOrAddedClass();
    };
  }, [leftRanges, props.leftCu, props.rightCu, rightRanges]);

  return (
    <div className={styles.playGround}>
      {arrows}
      {leftCu && (
        <div id="leftCu">
          <CUNode node={leftCu} />
        </div>
      )}
      {rightCu && (
        <div id="rightCu">
          <CUNode node={rightCu} />
        </div>
      )}
    </div>
  );
}
